package com.shinhye.mobilelottery.net.protocol;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.xmlpull.v1.XmlSerializer;

import android.util.Log;

import com.shinhye.mobilelottery.ConstantValue;

/*
 * <header>              
            <agenterid>889931</agenterid>
            <source>ivr</source>
            <compress>DES</compress>
 
            <messengerid>20131013101533000001</messengerid> 
            <timestamp>20131013101533</timestamp>
            <digest>7ec8582632678032d25866bd4bce114f</digest>

            <transactiontype>12002</transactiontype>
            <username>13200000000</username>
     </header>
 */

/**
 * 头信息封装
 * @author ShinHye
 * 2014-9-22 下午3:47:40
 */
public class Header {
	private Leaf messengerid;		// 标识
	private Leaf timestamp;			// 时间戳
	private Leaf transactiontype;	// 类型
	private Leaf digest;			// MD5加密
	private Leaf username;			// 用户名
	private Leaf agenterid;			// 代理商标示
	private Leaf source;			// 信息来源
	private Leaf compress;			// 是否des加密

	public Header() {
		this.messengerid = new Leaf("messengerid");
		this.timestamp = new Leaf("timestamp");
		this.transactiontype = new Leaf("transactiontype");
		this.digest = new Leaf("digest");
		this.username = new Leaf("username");

		this.agenterid = new Leaf("agenterid", ConstantValue.AGENTER_ID);
		this.source = new Leaf("source", ConstantValue.SOURCE);
		this.compress = new Leaf("compress", ConstantValue.COMPRESS);
	}

	public void serializer(XmlSerializer serializer, String body) {

		// 时间戳和标识
		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String num = new DecimalFormat("000000").format(new Random()
				.nextInt(999999) + 1);
		this.timestamp.setValue(time);
		this.messengerid.setValue(time + num);

		// 加密摘要信息
		String ori = time + ConstantValue.AGENT_PASSWORD + body;
		Log.i("Header", ori);
		String md5Hex = DigestUtils.md5Hex(ori);
		this.digest.setValue(md5Hex);

		//序列化
		try {
			serializer.startTag(null, "header");

			this.messengerid.serializer(serializer);
			this.timestamp.serializer(serializer);
			this.username.serializer(serializer);
			this.transactiontype.serializer(serializer);
			this.digest.serializer(serializer);
			this.agenterid.serializer(serializer);
			this.compress.serializer(serializer);
			this.source.serializer(serializer);

			serializer.endTag(null, "header");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Leaf getMessengerid() {
		return messengerid;
	}

	public Leaf getTimestamp() {
		return timestamp;
	}

	public Leaf getTransactiontype() {
		return transactiontype;
	}

	public Leaf getDigest() {
		return digest;
	}

	public Leaf getUsername() {
		return username;
	}
}